package cn.itcast.service.system.Impl;

import cn.itcast.dao.system.UserDao;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    public List<User> findAll(String companyId) {
        return userDao.findAll(companyId);
    }

    @Override
    public void save(User user) {
//        String passwordMing = user.getPassword();
        String passwordMing = RandomStringUtils.random(6,"utf-8");
        //此处用Md5Hash加密:原密码+邮箱+两次
        String passwordMi= new Md5Hash(passwordMing, user.getEmail(), 2).toString();
        user.setPassword(passwordMi);
        userDao.save(user);

        //发送邮件
        Map<String,String> map = new HashMap<>();
        map.put("to",user.getEmail());
        map.put("subject","恭喜成为SaaS货代平台会员");
        map.put("content","您的登录密码为:"+passwordMing);


        //routingKey,map
        amqpTemplate.convertAndSend("user.email",map);
    }

    @Override
    public User findById(String id) {
        return userDao.findById(id);
    }

    @Override
    public void update(User user) {
        userDao.update(user);
    }

    @Override
    public void deleteById(String id) {
        userDao.deleteById(id);
    }

    @Override
    public PageInfo findPage(String companyId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<User> list = userDao.findAll(companyId);
        return new PageInfo(list,5);
    }

    @Override
    public void changeRole(String userid, String[] roleIds) {

        userDao.deleteUserIdAndRoleId(userid);
        for (String roleId : roleIds) {

            userDao.saveUserIdAndRoleId(userid,roleId);
        }
    }

    @Override
    public List<String> findByUserId(String id) {
        return userDao.findByUserId(id);
    }

    @Override
    public User findByEmail(String email) {
        return userDao.findByEmail(email);
    }


    public static void main(String[] args) {
        String s = new Md5Hash("111111", "admin@export.com", 2).toString();
        System.out.println(s);
    }

}
